package com.example.springcloud.storage.service.impl;

import com.example.springcloud.storage.mapper.StorageMapper;
import com.example.springcloud.storage.service.StorageService;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 库存服务实现 - AT 模式
 */
@Slf4j
@Service
public class StorageServiceImpl implements StorageService {

    @Autowired
    private StorageMapper storageMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deduct(Long productId, Integer count) {
        log.info("库存服务 AT 模式：开始扣减库存");
        log.info("全局事务 XID: {}", RootContext.getXID());
        log.info("商品ID: {}, 扣减数量: {}", productId, count);

        int result = storageMapper.deduct(productId, count);
        if (result == 0) {
            String errorMsg = String.format("库存不足：商品ID=%d, 需要扣减=%d", productId, count);
            log.error(errorMsg);
            throw new RuntimeException(errorMsg);
        }

        log.info("库存扣减成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deductXa(Long productId, Integer count) {
        log.info("库存服务 XA 模式：开始扣减库存");
        log.info("全局事务 XID: {}", RootContext.getXID());
        log.info("商品ID: {}, 扣减数量: {}", productId, count);

        int result = storageMapper.deduct(productId, count);
        if (result == 0) {
            String errorMsg = String.format("库存不足：商品ID=%d, 需要扣减=%d", productId, count);
            log.error(errorMsg);
            throw new RuntimeException(errorMsg);
        }

        log.info("库存扣减成功");
    }
}

